package hbase.client;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 通过hbase api创建表和插入数据
 */
public class HbaseOperate {
    Configuration conf = null;
    Connection conn = null;

    @Before
    public void init() throws IOException {
        //获取一个配置文件对象
        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "linux121,linux122");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        //通过conf获取到hbase集群的连接
        conn = ConnectionFactory.createConnection(conf);
    }

    //创建t_fri_rel表
    @Test
    public void createTable() throws IOException {
        //获取HbaseAdmin对象用来创建表
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        //创建Htabledesc描述器，表描述器
        final HTableDescriptor rel = new HTableDescriptor(TableName.valueOf("t_fri_rel"));
        //指定列族
        rel.addFamily(new HColumnDescriptor("friends"));
        admin.createTable(rel);
        System.out.println("t_fri_rel表创建成功");
    }

    //插入数据
    @Test
    public void putData() throws IOException {
        //需要获取一个table对象
        Table table = conn.getTable(TableName.valueOf("t_fri_rel"));
        List<Put> puts = new ArrayList<Put>();
        //rowkey1
        Put put = new Put(Bytes.toBytes("uid1"));//指定rowkey
        put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid2"), Bytes.toBytes("uid2"));
        put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid5"), Bytes.toBytes("uid5"));
        put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid7"), Bytes.toBytes("uid7"));
        puts.add(put);
        //rowkey2
        Put put2 = new Put(Bytes.toBytes("uid2"));//指定rowkey
        put2.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid3"), Bytes.toBytes("uid3"));
        put2.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid1"), Bytes.toBytes("uid1"));
        put2.addColumn(Bytes.toBytes("friends"), Bytes.toBytes("uid6"), Bytes.toBytes("uid6"));
        puts.add(put2);
        table.put(puts);
        //关闭table对象
        table.close();
        System.out.println("插入数据到worker表成功！！");
    }


    //删除
    @Test
    public void deleteData() throws IOException {
        //需要获取一个table对象
        Table worker = conn.getTable(TableName.valueOf("t_fri_rel"));
        Delete delete = new Delete(Bytes.toBytes("uid1"));
        worker.delete(delete);
        worker.close();
        System.out.println("删除数据成功！！");
    }

    //释放连接
    @After
    public void realse() {
        if (conn != null) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
